<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: Seven
 * @Date: 2024-04-24 00:00:08
 * @LastEditors: Seven
 * @LastEditTime: 2024-04-24 19:01:47
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>闭包实现模块化-实现reduce+map方法</title>
</head>

<body>
    <script>
        // 任务: 利用闭包的模块化实现reduce和map方法

        // 一、reduce方法
        function module_A() {
            let arr = [10, 20, 30, 40, 50];
            return {
                get(index) {
                    if (!index && index !== 0) {
                        // 如果没有传入参数，就返回整个数组
                        return arr;
                    }
                    return arr[index];
                },
                getArrLength() {
                    return arr.length;
                },
                set(index, value) {
                    arr[index] = value;
                }
            }
        }
        let mA = module_A();

        let mB = (function () {
            return {
                reduce(callback, initValue) {
                    let arr2 = mA.get().slice();
                    let acc = initValue;
                    if (!initValue) { // 如果没传入初始值,累计器从下标为1开始计数
                        acc = mA.get(0);
                        for (let i = 1; i <arr2.length; i++) {
                            acc = callback && callback(acc, mA.get(i));
                        }
                        return acc;
                    }

                    // 如果有初始值
                    for (let i = 0; i < arr2.length; i++) {
                        acc = callback && callback(acc, mA.get(i), i, mA.get());
                    }
                    return acc;
                },

                map(callback) {
                    let arr2 = mA.get().slice();
                    for (let i = 0; i < arr2.length; i++) {
                        arr2[i] = callback && callback(mA.get(i), i, mA.get());
                    }
                    return arr2;
                }
            }
        })();

        let mC = (function () {
            // reduce方法调用
            let red = mB.reduce(function (acc, item, index, arr) {
                return acc + item;
            });

            let red2 = mB.reduce(function (acc, item, index, arr) {
                acc[index] = item;
                return acc;
            }, {});
            console.log(red, red2);

            // map方法调用
            let map1 = mB.map(function(item,index,arr) {
                return item * 2;
            });
            let map2 = mB.map(function(item,index,arr) {
                return {item,index,arr};
            })
            console.log(map1,map2);

        })();



        // [].reduce(function(acc,item,index,arr){
        //     return acc + item;
        // },0);

        // [].map(function() {
        //     return item * 2;
        // })
    </script>
</body>

</html>